// store/modules/notification.js
import { get , del, put} from '@/http/http';

const state = {
  notifications: [],       // 通知列表
  currentPage: 1,          // 当前页码
  pageSize: 10,            // 每页数量
  total: 0,                // 总记录数
  searchParams: {          // 搜索参数
    username: '',
    consultantName: ''
  },
  loading: false,          // 加载状态
  error: null              // 错误信息
};

const mutations = {
  // 设置通知列表数据
  SET_NOTIFICATIONS(state, payload) {
    state.notifications = payload.data;
    state.total = payload.total;
  },
  
  // 更新分页参数
  SET_PAGE(state, { page, size }) {
    state.currentPage = page;
    state.pageSize = size;
  },
  
  // 更新搜索条件
  SET_SEARCH(state, params) {
    state.searchParams = { ...state.searchParams, ...params };
  },
  
  // 设置加载状态
  SET_LOADING(state, isLoading) {
    state.loading = isLoading;
  },
  
  // 设置错误信息
  SET_ERROR(state, error) {
    state.error = error;
  }
};

const actions = {
  // 获取通知列表
  async fetchNotifications({ commit, state }) {
    commit('SET_LOADING', true);
    try {
      const params = {
        pageNum: state.currentPage,
        pageSize: state.pageSize,
        ...state.searchParams
      };
      
      const response = await get('/hqy/notifications', params);
      console.log('notice',response);
      
      commit('SET_NOTIFICATIONS', {
        data: response.data.list,  // 根据实际返回结构调整
        total: response.data.total
      });
    } catch (error) {
      commit('SET_ERROR', error.message);
      console.error('获取通知失败:', error);
    } finally {
      commit('SET_LOADING', false);
    }
  },
  // 获取通知列表
  async fetchNotificationsC({ commit, state }) {
    commit('SET_LOADING', true);
    try {
      const params = {
        pageNum: state.currentPage,
        pageSize: state.pageSize,
        ...state.searchParams
      };
      
      const response = await get(`/hqy/notifications/${JSON.parse(sessionStorage.getItem('consultant')).id}`, params);
      console.log('notice',response);
      
      commit('SET_NOTIFICATIONS', {
        data: response.data.list,  // 根据实际返回结构调整
        total: response.data.total
      });
    } catch (error) {
      commit('SET_ERROR', error.message);
      console.error('获取通知失败:', error);
    } finally {
      commit('SET_LOADING', false);
    }
  },

  // 更新搜索条件并刷新
  updateSearchParams({ commit, dispatch }, params) {
    commit('SET_SEARCH', params);
    commit('SET_PAGE', { page: 1, size: state.pageSize });
    dispatch('fetchNotifications');
  },

  // 分页变化处理
  handlePageChange({ commit, dispatch }, { page, size }) {
    commit('SET_PAGE', { page, size });
    dispatch('fetchNotifications');
  },
  // 新增删除action
  async deleteNotification({ commit }, id) {
    try {
      commit('SET_LOADING', true);
      const res = await del(`/hqy/notifications/${id}`);
      
      alert(res.data);
    //   两种更新方式任选其一：
    //   方式1：直接过滤本地数据（适用于少量数据）
      commit('SET_NOTIFICATIONS', {
        data: state.notifications.filter(item => item.id !== id),
        total: state.total - 1
      });

      // 方式2：重新获取最新数据（推荐用于分页场景）
    //   await this.dispatch('fetchNotifications');
      
    } catch (error) {
      commit('SET_ERROR', error.message);
      throw new Error('删除失败');
    } finally {
      commit('SET_LOADING', false);
    }
  },
  // 新增更新action
  async updateNotification({ commit }, payload) {
    commit('SET_LOADING', true);
    try {
      const response = await put(`/hqy/notifications/${payload.id}`, payload);
      
      // 方式1：直接更新本地数据（快速响应）
    //   commit('UPDATE_NOTIFICATION', {
    //     updatedData: response.data,
    //     index: state.notifications.findIndex(item => item.id === payload.id)
    //   });

      alert(response.data)

      return response;
    } catch (error) {
      commit('SET_ERROR', '更新失败: ' + error.message);
      throw error;
    } finally {
      commit('SET_LOADING', false);
    }
  }
};

const getters = {
  // 获取当前页数据
  currentNotifications: state => state.notifications,
  
  // 分页信息
  pagination: state => ({
    current: state.currentPage,
    pageSize: state.pageSize,
    total: state.total
  }),
  
  // 搜索条件
  searchConditions: state => state.searchParams,
  
  // 加载状态
  isLoading: state => state.loading
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
};